{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        {#左右排序#}
        }

        .panel-default .panel-heading a {
            text-decoration: none;
        }

        .panel-default .panel-heading span {
            padding: 0 50px;
        }

        {#文件上传按钮#}
        .panel-default .panel-heading .function .upload {
            overflow: hidden;
            position: relative;
        }

        .panel-default .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .progress-error {
            color: red;
        }
    </style>
{% endblock css %}

{% block content %}
    <div class="container-fluid">
        <div class="panel panel-default">

            <!-- 文件导航栏 -->
            <div class="panel-heading">
                <div>
                    <a href="{% url 'web:manage:file' request.tracer.project.id %}">
                        <i class="fa fa-home" aria-hidden="true"></i> 文件夹
                    </a>
                    {% for record in breadcrumb_list %}
                        <a href="{% url 'web:manage:file' request.tracer.project.id %}?folder={{ record.id }}">
                            <i class="fa fa-caret-right" aria-hidden="true"></i> {{ record.name }}
                        </a>
                    {% endfor %}
                </div>
                <div class="function">
                    <div class="btn btn-primary btn-xs upload">
                        <!--图标-->
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile"/>
                    </div>

                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addmodal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                </div>
            </div>

            <!-- Table -->
            <table class="table">
                <thead>
                <tr>
                    <th>名称</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody id="rowList">
                {% for item in file_obj_list %}
                    <tr>
                        <td>
                            {% if item.file_type == 1 %}
                                <i class="fa fa-file" aria-hidden="true"></i>
                                {{ item.name }}
                            {% else %}
                                <a href="{% url 'web:manage:file' request.tracer.project.id %}?folder={{ item.id }}">
                                    <i class="fa fa-folder" aria-hidden="true"></i>
                                    {{ item.name }}
                                </a>
                            {% endif %}

                        </td>

                        <td>
                            {% if item.file_type == 1 %}
                                {#                                {{ item.file_size }}#}
                                {#                                MB显示#}
                                {% widthratio item.file_size 1024 1 %} KB
                            {% else %}
                                -
                            {% endif %}
                        </td>
                        <td>{{ item.update_user.username }}</td>
                        <td>{{ item.modify_datetime }}</td>
                        <td>
                            {% if item.file_type == 2 %}
                                <a class="btn btn-default btn-xs"
                                   data-toggle="modal"
                                   data-target="#addmodal"
                                   data-name="{{ item.name }}"
                                   data-fid="{{ item.id }}"
                                   data-whatever="编辑文件夹">
                                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
                            {% elif item.file_type == 1 %}
                                <a class="btn btn-default btn-xs download" href="{% url 'web:manage:file_download' request.tracer.project.id %}?fid={{ item.id }}">
                                    <i class="fa fa-download" aria-hidden="true"></i>
                                </a>
                            {% endif %}
                            <a>
                                <a class="btn btn-default btn-xs"
                                   data-toggle="modal"
                                   data-fid="{{ item.id }}"
                                   data-target="#deletemodal">
                                    <i class="fa fa-trash" aria-hidden="true"></i></a>

                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="addmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                    </div>
                    <div class="modal-body">
                        <form id="form">
                            <input type="text" name="fid" id="fid" class="hidden">
                            {% csrf_token %}
                            {% for field in form %}
                                <div class="form-group">
                                    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                    {{ field }}
                                    <span class="error-msg">{{ field.errors.0 }}</span>
                                </div>
                            {% endfor %}
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" id="btnFormSubmit" class="btn btn-primary">确定</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="deletemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="alert alert-danger alert-dismissible fade in" role="alert">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4>是否全部删除？</h4>
                    <p style="padding-top: 20px; padding-bottom: 20px;">文件夹中所有的内容都会被删除</p>
                    <p style="text-align: right">
                        <a type="button" class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取消</a>
                        <button type="button" id="btnDelete" class="btn btn-danger btn-sm">确定</button>
                    </p>
                </div>
            </div>
        </div>

        <div id="uploadProgress" class="upload-progress hide">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <i class="fa fa-cloud-upload"></i> 上传进度
                </div>
                <div class="panel-body">
                    <table class="table">
                        <tbody id="progressList">
                        <!--通过下方模板导入-->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100" style="width: 0;">
                            0
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="update_user_username"></td>
                <td class="update_datetime"></td>
                <td>

                    <a class="btn btn-default btn-xs download" href="{% url 'web:manage:file_download' request.tracer.project.id %}?fid=">
                        <i class="fa fa-download" aria-hidden="true"></i>
                    </a>
                    <a class="btn btn-default btn-xs delete" data-toggle="modal" data-target="#deletemodal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
{% endblock content %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        $(function () {
            // 当前文件所在文件夹ID
            var CURRENT_FOLDER_ID = '{{ folder_obj.id }}';

            // 删除文件夹
            $('#btnDelete').click(function () {
                // 获取需要删除的ID
                $.ajax({
                    url: '{% url 'web:manage:file_delete' request.tracer.project.id %}',
                    type: 'get',
                    data: {"fid": $(this).attr('fid')}
                }).done(function (data) {
                    console.log(data.msg);
                    if (data.code === 200) {
                        location.href = location.href;
                    }
                }).fail(function () {
                    console.log("网络出现错误");
                })
            })
            //提交模态框数据
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: 'POST',
                    data: $('#form').serialize()
                }).done(function (data) {
                    console.log(data.msg);
                    if (data.code === 200) {
                        location.href = location.href;
                    } else {
                        $.each(data.msg, function (k, v) {
                            $('#id_' + k).next().text(v[0]);
                        })
                    }
                }).fail(function () {
                    console.log("网络出现错误");
                })
            });

            // 添加和修改模态框处理
            $('#addmodal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget)
                var recipient = button.data('whatever');
                var name = button.data('name');
                var fid = button.data('fid');
                var modal = $(this);
                modal.find('.modal-title').text(recipient);

                if (fid) {
                    // 编辑
                    $('#id_name').val(name);
                    $('#fid').val(fid);
                } else {
                    // 新建
                    modal.find('.error-msg').empty();
                    $('#form')[0].reset();
                }

            });

            // 删除模态框处理
            $('#deletemodal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget)
                var fid = button.data('fid');
                $('#btnDelete').attr('fid', fid);
            });

            // 文件上传事件
            $('#uploadFile').change(function () {
                var filelist = $(this)[0].files;    // 获取到所有文件

                // 每次上传都清空进度条
                $('#progressList').empty();


                // 获取每次上传的文件的大小及名称
                var checkFileList = [];
                $.each(filelist, function (index, fileObj) {
                    checkFileList.push({'name': fileObj.name, 'size': fileObj.size})
                });

                // 初始化实例 -- 并对数据进行容量大小进行校验，没有问题就返回临时秘钥，否则返回错误信息
                var cos = new COS({
                    getAuthorization: function (options, callback) {
                        // 异步获取临时密钥--同时校验数据
                        $.post('{% url 'web:manage:cos_credentials' request.tracer.project.id %}',
                            // post发送秦秋文件
                            JSON.stringify(checkFileList)
                            , function (data) {
                                if (data.code === 200) {
                                    var credentials = data.data && data.data.credentials;
                                    if (!data.data || !credentials) return console.error('credentials invalid');
                                    callback({
                                        TmpSecretId: credentials.tmpSecretId,
                                        TmpSecretKey: credentials.tmpSecretKey,
                                        XCosSecurityToken: credentials.sessionToken,
                                        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                                        StartTime: data.data.startTime, // 时间戳，单位秒，如：1580000000
                                        ExpiredTime: data.data.expiredTime, // 时间戳，单位秒，如：1580000900
                                    });

                                    // 授权成功，显示进度条
                                    $('#uploadProgress').removeClass('hide')
                                } else {
                                    alert(data.msg);
                                }
                            });
                    }
                });

                $.each(filelist, function (index, fileObj) {
                    // 获取时间戳用于文件名
                    var file_key = (new Date()).getTime() + '_' + fileObj.name;

                    // 进度条处理 -- clone 表示将当前标签复制一份
                    var $tr = $('#progressTemplate').find('tr').clone();
                    $tr.find('.name').text(fileObj.name);

                    // 添加到进度条中
                    $('#progressList').append($tr);

                    // 上传文件
                    cos.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                        Region: '{{ request.tracer.project.region }}',     /* 存储桶所在地域，必须字段 */
                        Key: file_key,              /* 必须 */
                        StorageClass: 'STANDARD',
                        Body: fileObj, // 上传文件对象
                        onProgress: function (progressData) {
                            {#var dataDict = JSON.stringify(progressData);#}
                            var percent = progressData.percent * 100 + '%'
                            $tr.find('.progress-bar').text(percent);
                            $tr.find('.progress-bar').css({'width': percent});
                        }
                    }, function (err, data) {
                        console.log(err || data);
                        // 上传成功之后向后台发送数据并存储
                        if (data && data.statusCode === 200) {
                            // 上传成功 数据写入数据库
                            $.post('{% url 'web:manage:file_post' request.tracer.project.id %}',
                                // 文件名称name 文件大小file_size  文件在cos中存储的地址key 当前文件所在的文件夹地址parent
                                {
                                    'name': fileObj.name,
                                    'file_size': fileObj.size,
                                    'key': file_key,
                                    'parent': CURRENT_FOLDER_ID,
                                    'file_path': data.Location,
                                },
                                function (data) {
                                    // 回调函数
                                    var $newTr = $('#rowTpl').find('tr').clone();
                                    $newTr.find('.name').text(data.msg.name);
                                    $newTr.find('.file_size').text(data.msg.file_size);
                                    $newTr.find('.update_user_username').text(data.msg.username);
                                    $newTr.find('.update_datetime').text(data.msg.modify_datetime);
                                    $newTr.find('.delete').attr('data-fid', data.msg.id);
                                    // 给文件下载使用  修复文件下载，不通过json进行返回
                                    {#$newTr.find('.download').attr('fid', data.msg.id);#}
                                    href = $newTr.find('.download').attr('href');
                                    href += data.msg.id;
                                    $newTr.find('.download').attr('href', href);
                                    $('#rowList').append($newTr);
                                    // 清理进度条
                                    $tr.remove();
                                })
                        } else {
                            $tr.find('.progress-error').text("上传失败");
                        }

                    });
                });
            });

            // 文件下载
            {% comment %}
            $('.download').click(function (){
                fid = $(this).attr('fid')
                $.get('{% url 'web:manage:file_download' request.tracer.project.id %}',
                    {
                        'fid': fid
                    },
                    function (data){
                        if(data.code === 200){
                            location.href = data.msg;
                        }else{
                            alert(data.msg);
                        }
                    });
            });
            {% endcomment %}
        })
    </script>
{% endblock js %}